package com.yi.gostockgo.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yi.gostockgo.common.BaseMessage;
import com.yi.gostockgo.common.email.JMailBean;
import com.yi.gostockgo.common.email.JMailSend;
import com.yi.gostockgo.common.email.PhoneCodeUntil;
import com.yi.gostockgo.controller.vo.GoUserVo;
import com.yi.gostockgo.pojo.GoUser;
import com.yi.gostockgo.service.GoUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * <p>
 * 股民信息 前端控制器
 * </p>
 *
 * @author liandyao
 * @since 2020-04-19
 */
@Api(description = "Restful风格*****股民信息(会员)接口*****")
@RestController
@RequestMapping("/goUser")
public class GoUserController {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    GoUserService goUserService ;

    /**
     * 传入可以是手机号userPhone,邮箱号userEmail,会员号userAccount,三者任选其一,密码userPassword
     * @param userName
     * @param userPassword
     * @param valiCode
     * @return
     */
    @ApiOperation(value = "登录接口" ,  notes="用户名和密码,valiCode验证码可为空")
    @PostMapping("/login")
    public BaseMessage login(String userName,String userPassword,String valiCode){
        if(StringUtils.isEmpty(userName)){
            return BaseMessage.getBaseFail().setMsg("账号不能为空!");
        }
        if(StringUtils.isEmpty(userPassword)){
            return BaseMessage.getBaseFail().setMsg("密码不能为空!");
        }

        //验证码目前暂时不开发


        GoUser user =  setUserName(userName,userPassword);

        return goUserService.login(user);
    }

    /**
     * 设置用户
     * @param userName
     * @param userPassword
     * @return
     */
    private GoUser setUserName(String userName,String userPassword){
        GoUser user = new GoUser();

        user.setUserAccount(userName);
        user.setUserEmail(userName);
        user.setUserPhone(userName);
        user.setUserPassword(userPassword);
        return user ;
    }

    @ApiOperation(value = "检查账号是否存在" ,  notes="传入可以是手机号userPhone,邮箱号userEmail,会员号userAccount,三者任选其一")
    @GetMapping(value = "/checkUser/{name}")
    public BaseMessage checkUser(@PathVariable String name, HttpServletRequest request){
        String agent=request.getHeader("User-Agent").toLowerCase();
        System.out.println(agent);

        /*
        电脑打开是          mozilla/5.0 (iphone; cpu iphone os 13_2_3 like mac os x) applewebkit/605.1.15 (khtml, like gecko) version/13.0.3 mobile/15e148 safari/604.1
        qq打开             mozilla/5.0 (linux; android 10; lya-al00 build/huaweilya-al00l; wv) applewebkit/537.36 (khtml, like gecko) version/4.0 chrome/66.0.3359.126 mqqbrowser/6.2 tbs/045130 mobile safari/537.36 v1_and_sq_7.1.0_0_tim_d tim/3.0.0.2860 qq/6.5.5  nettype/wifi webp/0.3.0 pixel/1080
        手机浏览器打开      mozilla/5.0 (linux; android 10; lya-al00) applewebkit/537.36 (khtml, like gecko) chrome/78.0.3904.108 huaweibrowser/10.1.0.300 mobile safari/537.36


         */


        if(StringUtils.isEmpty(name)){
            return BaseMessage.getBaseFail().setMsg("账号不能为空!");
        }
        GoUser user =  setUserName(name,null);
        return goUserService.checkUser(user) ;
    }



    @ApiOperation(value = "注册接口" ,  notes="传入可以是手机号userPhone,邮箱号userEmail,会员号userAccount,三者任选其一,密码userPassword,remark邀请码可不填")
    @PostMapping("/regist")
    public BaseMessage regist(@RequestBody GoUserVo user, HttpSession session){
        if(StringUtils.isEmpty(user.getUserPassword())){
            return BaseMessage.getBaseFail().setMsg("密码不能为空!");
        }


        //判断是哪种方式注册
        GoUser po = new GoUser();
        String userName = user.getUserName();
        if("1".equals(user.getRadio())){ //手机
            po.setUserPhone(userName);
            String code = (String)session.getAttribute("code");
            if(!user.getSms().equals(code)){
                return BaseMessage.getBaseFail().setMsg("验证码错误!");
            }
        }else if("2".equals(user.getRadio())){//邮箱
            po.setUserEmail(userName);
            String code = (String)session.getAttribute("code");
            if(!user.getSms().equals(code)){
                return BaseMessage.getBaseFail().setMsg("验证码错误!");
            }
        }else if("3".equals(user.getRadio())){
            po.setUserAccount(userName);
        }
        //将相同的属性复制
        BeanUtils.copyProperties(user,po);

        return goUserService.save(po)?BaseMessage.getBaseSuccess():BaseMessage.getBaseFail();
    }

    @ApiOperation("根据ID获取用户详情")
    @ApiParam(name = "id",value = "传入ID")
    @RequestMapping(method = RequestMethod.GET,value = "/{id}")
    public BaseMessage getGoUser(@PathVariable String id) {
        GoUser user = goUserService.getById(id);
        if(user==null){
            return BaseMessage.getBaseFail();
        }else{
            return BaseMessage.getBaseSuccess().setObject(user);
        }

    }

    @Resource
    JMailSend jMailSend;

    @Resource
    JMailBean jmail ;

    /**
     *
     * @param type 1 手机  2 邮箱
     * @param name 手机或者邮箱名
     * @param session
     * @return
     */
    @ApiOperation("发送验证码 type:1 发送手机验证码  2 发送邮箱验证码 ")
    @GetMapping("/sendSms/{type}/{name}")
    public BaseMessage sendSms(@PathVariable Integer type, @PathVariable String name, HttpSession session){
        String code = PhoneCodeUntil.getRandonString(4);//生成验证码
        session.setAttribute("code",code); //将验证码放入到session中
        logger.info("验证码......................."+code);
        if(type==1){

        }else if(type==2){
            jmail.setContent(jmail.getSmsMsg()+code);
            jmail.setRecipient(name);
            jMailSend.sendSimpleMail(jmail);

            logger.info("邮件发送成功......................."+jmail.toString());
        }

        return BaseMessage.getBaseSuccess();
    }

    /**
     * 根据用户注册帐号以及邀请码查询用户数据
     * @param goUserVo
     * @return 用户数据
     */
    @ApiOperation("根据用户注册帐号以及邀请码查询用户数据")
    @GetMapping("/pagingQuery")
    public BaseMessage pagingQuery(GoUserVo goUserVo) {
        return BaseMessage.getBaseSuccess(goUserService.pagingQuery(goUserVo));
    }


    /**
     * 根据id更新状态
     * @param id 用户id
     * @param state 状态码
     * @return 更新结果
     */
    @ApiOperation("根据id更新状态")
    @PutMapping("/{id}/{state}")
    public BaseMessage updateState(@PathVariable String id,@PathVariable String state) {
        UpdateWrapper<GoUser> wrapper = new UpdateWrapper<GoUser>();
        wrapper.eq("user_id", id);
        wrapper.set("state", state);
        boolean flag = goUserService.update(wrapper);
        return flag ? BaseMessage.getBaseSuccess("更新成功", null) : BaseMessage.getBaseFail("更新失败");
    }


    @DeleteMapping("/{id}")
    public BaseMessage deleteUser(@PathVariable String id) {
        UpdateWrapper<GoUser> wrapper = new UpdateWrapper<GoUser>();
        wrapper.set("isva", 0);
        wrapper.eq("user_id", id);
        boolean flag = goUserService.update(wrapper);
        return flag ? BaseMessage.getBaseSuccess("删除成功", null) : BaseMessage.getBaseFail("删除失败");
    }
}

